<template>
  <el-tag
    v-if="tag"
    :type="tag.type || ''"
    :effect="tag.effect || 'light'"
    :size="size"
  >{{ tag.label }}</el-tag>
  <span v-else>{{ defaultLabel }}</span>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { getDictData } from '@/utils/dict'

const props = defineProps({
  // 字典类型
  dictType: {
    type: String,
    required: true
  },
  // 字典值
  value: {
    type: [Number, String, Boolean],
    required: true
  },
  // 大小
  size: {
    type: String,
    default: 'default'
  },
  // 默认标签
  defaultLabel: {
    type: String,
    default: ''
  }
})

// 标签对象
const tag = ref(null)

// 根据字典类型和值获取标签
const getTag = async () => {
  const dictData = await getDictData(props.dictType)
  
  // 查找匹配的字典项
  const dictItem = dictData.find(item => item.value === props.value)
  
  if (dictItem) {
    // 根据字典项的样式类确定Tag组件的type
    let type = ''
    if (dictItem.listClass) {
      // 常见的样式类映射到Element Plus的Tag类型
      const classMap = {
        'primary': 'primary',
        'success': 'success',
        'info': 'info',
        'warning': 'warning',
        'danger': 'danger'
      }
      type = classMap[dictItem.listClass] || ''
    }
    
    tag.value = {
      label: dictItem.label,
      type: type,
      effect: 'light'
    }
  } else {
    tag.value = null
  }
}

// 监听属性变化
watch(
  () => [props.dictType, props.value],
  () => {
    getTag()
  },
  { immediate: false }
)

// 组件挂载时获取标签
onMounted(() => {
  getTag()
})
</script> 